// 数据懒加载
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'
// target dom对象
// apiFn   aapi函数
export const useLazyData = (apiFn) =>{
    const result = ref([])
    const target = ref(null)
    // stop   停止观察
    const { stop } = useIntersectionObserver(
        //监听的目标元素
      target,
      //isIntersecting  是否进入可视区
      ([{ isIntersecting }], observerElement) => {
        if(isIntersecting) {
            //进入可视区停止观察
            stop ()
            //调用api函数，获取数据
            apiFn().then(data => {
                result.value = data.result
            })
        }
    },
    //相交比例
    {threshold: 0}
    )
return {result,target}
}


//定时器函数

/**
 * 支付倒计时函数
 */
export const usePayTime = () => {
    // 倒计时逻辑
    const time = ref(0)
    const timeText = ref('')
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      timeText.value = dayjs.unix(time.value).format('mm分ss秒')
      if (time.value <= 0) {
        pause()
      }
    }, 1000, false)
    onUnmounted(() => {
      pause()
    })
  
    // 开启定时器 countdown 倒计时时间
    const start = (countdown) => {
      time.value = countdown
      timeText.value = dayjs.unix(time.value).format('mm分ss秒')
      resume()
    }
  
    return {
      start,
      timeText
    }
  }